﻿using System;
using ASPNETVN.PORTAL.Components.Helpers;
using ASPNETVN.PORTAL.Components.UI;
using ASPNETVN.PORTAL.Components.Security;
using System.Net.Mail;
using System.Text;
using System.Collections;
using ASPNETVN.PORTAL.Components.Share.Controls;
using ASPNETVN.PORTAL.Components.Share;

namespace ASPNETVN.PORTAL.Modules.DOWNLOAD.Controls
{
    public partial class Detail : ModulePage
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            var commentControl = (PostComment) PostComment1;
            commentControl.Posted += PostComment_Posted;

            var recaptcha = (Recaptcha)RecaptchaDownload;
            recaptcha.Validate += RecaptchaDownload_Validate;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack == false)
            {
                hlSignIn.NavigateUrl = "~/SignIn.aspx?ReturnUrl=" + Server.UrlEncode(Request.RawUrl);
                pnlSignIn.Visible = !PortalSecurity.CurrentUser.Identity.IsAuthenticated;
               
                Hashtable settings = this.Settings;

                // PostComment1.Visible = Boolean.Parse(settings["RequireAuthentication"].ToString());
                if (Boolean.Parse(settings["RequireAuthentication"].ToString()))
                {
                    pnlSignIn.Visible = !PortalSecurity.CurrentUser.Identity.IsAuthenticated;
                    
                    if (PortalSecurity.CurrentUser.Identity.IsAuthenticated)
                    {
                        if (Boolean.Parse(settings["RequireCheckCode"].ToString()))
                        {
                            pnlCheckCode.Visible = true;
                            pnlDownloads.Visible = false;
                        }
                        else
                        {
                            pnlCheckCode.Visible = false;
                            pnlDownloads.Visible = true;
                        }
                    }
                    else
                    {
                        pnlCheckCode.Visible = false;
                        pnlDownloads.Visible = false;
                    }
                }
                else
                {
                    pnlSignIn.Visible = false;
                    if (Boolean.Parse(settings["RequireCheckCode"].ToString()))
                    {
                        pnlCheckCode.Visible = true;
                        pnlDownloads.Visible = false;
                    }
                    else
                    {
                        pnlCheckCode.Visible = false;
                        pnlDownloads.Visible = true;
                    }
                }

                if (this.ItemID > 0)
                {
                    Components.Item.IncreaseTotalViews(this.ItemID);
                    Components.Item item = Components.Item.Load(this.ItemID);                    
                    if (item != null)
                    {
                        // Build page link.
                        PageLink pagelink = (PageLink)this.ParentControl.FindControl("MainPageLink");

                        int categoryID = item.CategoryID;
                        Category category = Category.Load(categoryID);
                        if (category != null)
                        {
                            Category parentCategory = Category.Load(category.ParentID);
                            if (parentCategory != null)
                            {
                                pagelink.AddLink(parentCategory.Title, "#");

                                string url = ResolveClientUrl(HttpUrlBuilder.BuildModulePageUrl(this.ModuleID, 0, ModulePages.ItemList, "categoryid={0}", category.ID));
                                pagelink.AddLink(category.Title, url);

                                pagelink.AddLink(item.Title, "#");
                            }
                        }

                        SpanTotalViews.Visible = Convert.ToBoolean(settings["DisplayOptionTopView"].ToString());
                        SpanTotalDownloads.Visible = Convert.ToBoolean(settings["DisplayOptionTopDownload"].ToString());
                        SpanTotalComments.Visible = Convert.ToBoolean(settings["DisplayOptionTopComment"].ToString());

                        lblTitle.Text = item.Title;
                        lblCreatedDate.Text = item.CreatedDate.ToString();
                        lblCreatedBy.Text = item.CreatedBy;
                        lblTotalDownloads.Text = item.TotalDownloads.ToString("N0");
                        lblTotalComments.Text = item.TotalComments.ToString("N0");
                        lblTotalViews.Text = item.TotalViews.ToString("N0");
                        imgImage.ImageUrl = item.CoverImageUrl;
                        imgImage.Visible = item.CoverImageUrl.Trim().Length > 0;
                        HyperLinkLighBox.NavigateUrl = item.CoverImageUrl;
                        HyperLinkLighBox.Visible = item.CoverImageUrl.Trim().Length > 0;
                        lblBody.Text = Server.HtmlDecode(item.Description);

                        var commentListControl = (CommentList)CommentList1;
                        commentListControl.Title = "Trả lời: " + lblTitle.Text;

                        var postCommentControl = (PostComment) PostComment1;
                        postCommentControl.Title = "Trả lời: " + lblTitle.Text;

                        // Set title text.
                        this.SetTitleText(item.Title);
                    }
                }
            }
        }

        protected void btnSendMail_Click(object sender, EventArgs e)
        {
            if (this.ItemID > 0)
            {
                string from = "webmaster@asp.net.vn";
                if (PortalSecurity.CurrentUser.Identity.IsAuthenticated)
                    from = PortalSecurity.CurrentUser.Identity.Email;


                StringBuilder body = new StringBuilder();
                body.Append("Xin chao!<br><br>");
                body.Append("Toi tim thay thong tin nay can chia se voi ban. Toi nghi ban quan tam.<br><br>");

                body.AppendFormat("Xem chi tiet tai day: <a href='{0}'>{0}</a><br><br>", Request.RawUrl);

                body.AppendFormat("- Tieu de: <strong>{0}</strong><br><br>", lblTitle.Text);
                body.AppendFormat("- Thong diep: {0}<br><br>", txtMessage.Text);

                body.Append("<br>Chuc ban vui ve!");

                string[] emails = txtEmails.Text.Split(';');
                foreach (string email in emails)
                {
                    MailHelper.SendMail(from, email, "", "", "Thong tin chia se", body.ToString(), MailPriority.Normal);
                }
                txtEmails.Text = txtMessage.Text = string.Empty;
            }
        }

        protected void PostComment_Posted(object sender, EventArgs e)
        {
            var commentListControl = (CommentList) CommentList1;
            commentListControl.DataBind();
            Components.Item.IncreaseTotalComments(this.ItemID);
            
            // Reload new data.
            commentListControl.Reload();
        }

        protected void RecaptchaDownload_Validate(object sender, EventArgs e)
        {
            var recaptcha = (Recaptcha) RecaptchaDownload;
            if (recaptcha.IsValid)
            {
                Components.Item.IncreaseTotalDownloads(this.ItemID);
                pnlCheckCode.Visible = false;
                pnlDownloads.Visible = true;
            }
        }
    }
}